<template>
	<view class="container">
		<view class="form-section">
			<text class="section-title">编辑通知公告</text>
			<text class="section-desc">请编辑以下信息，更新裁判通知公告内容</text>
			
			<view class="form-item">
				<text class="form-label required">公告标题</text>
				<input class="form-input" type="text" v-model="formData.title" placeholder="请输入公告标题" />
			</view>
			
			<view class="form-item">
				<text class="form-label required">公告内容</text>
				<view class="textarea-container">
					<textarea class="form-textarea" v-model="formData.content" placeholder="请输入公告详细内容（支持Markdown格式）" maxlength="-1" />
				</view>
			</view>
			
			<view class="form-item">
				<text class="form-label required">公告摘要</text>
				<input class="form-input" type="text" v-model="formData.summary" placeholder="请输入简短摘要，不超过200字" />
			</view>
			
			<!-- 公告类型 -->
			<view class="form-item">
				<text class="form-label required">公告类型</text>
				<picker class="form-picker" :value="categoryIndex" :range="categoryOptions" @change="bindCategoryChange">
					<view class="picker-value">
						{{ categoryOptions[categoryIndex] }}
					</view>
				</picker>
			</view>
			
			<!-- 添加类型选择：普通公告还是活动通知 -->
			<view class="form-item">
				<text class="form-label required">内容类型</text>
				<picker class="form-picker" :value="noticeTypeIndex" :range="noticeTypeOptions" @change="bindNoticeTypeChange">
					<view class="picker-value">
						{{ noticeTypeOptions[noticeTypeIndex] }}
					</view>
				</picker>
			</view>
			
			<!-- 公告标签 -->
			<view class="form-item">
				<text class="form-label required">公告标签</text>
				<input class="form-input" type="text" v-model="formData.tags" placeholder="请输入标签，多个标签用逗号分隔" />
			</view>
			
			<view class="form-item">
				<text class="form-label required">发布日期</text>
				<picker class="form-picker" mode="date" :value="formData.publishDate" start="2020-01-01" :end="endDate" @change="bindDateChange">
					<view class="picker-value">
						{{ formData.publishDate }}
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">截止日期</text>
				<picker class="form-picker" mode="date" :value="formData.endDate" :start="formData.publishDate" @change="bindEndDateChange">
					<view class="picker-value">
						{{ formData.endDate || '请选择截止日期（可选）' }}
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">重要程度</text>
				<picker class="form-picker" :value="importanceIndex" :range="importanceOptions" @change="bindImportanceChange">
					<view class="picker-value">
						{{ importanceOptions[importanceIndex] }}
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">显示在首页轮播</text>
				<view class="switch-container">
					<switch :checked="formData.showInBanner" @change="bindShowInBannerChange" color="#1BAE76" />
					<text class="switch-label">{{ formData.showInBanner ? '显示' : '不显示' }}</text>
				</view>
			</view>
		</view>
		
		<view class="submit-section">
			<button class="submit-btn" @click="submitForm" :disabled="submitting">{{ submitting ? '更新中...' : '更新公告' }}</button>
		</view>
	</view>
</template>

<script>
	import '../admin/app.css';
	export default {
		data() {
			const today = new Date();
			const year = today.getFullYear();
			const month = (today.getMonth() + 1).toString().padStart(2, '0');
			const day = today.getDate().toString().padStart(2, '0');
			const currentDate = `${year}-${month}-${day}`;
			
			return {
				noticeId: '',
				userInfo: null,
				formData: {
					title: '',
					content: '',
					summary: '',
					category: '赛事通知',
					tags: '',
					publishDate: currentDate,
					endDate: '',
					importance: '普通',
					language: 'zh-CN',
					type: 'notice',
					isPublished: true,
					showInBanner: false,
					bannerImage: {}
				},
				
				// 当前日期及最大日期
				currentDate: currentDate,
				endDate: `${year + 1}-${month}-${day}`,
				
				// 下拉菜单选项
				categoryOptions: ['赛事通知', '规则解读', '裁判培训', '其他通知'],
				categoryIndex: 0,
				
				noticeTypeOptions: ['公告通知', '活动通知'],
				noticeTypeIndex: 0,
				
				importanceOptions: ['普通', '重要'],
				importanceIndex: 0,
				
				languageOptions: ['简体中文', '英文'],
				languageIndex: 0,
				
				// 表单状态
				submitting: false,
				loading: true
			}
		},
		onLoad(options) {
			if (options.id) {
				this.noticeId = options.id;
			} else {
				this.handleError('未指定公告ID');
				return;
			}
			
			// 获取用户信息并加载公告数据
			this.getUserInfo();
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						let userInfo = JSON.parse(userInfoStr);
						
						// 确保userInfo对象包含_id字段
						if (!userInfo._id && userInfo.userId) {
							userInfo._id = userInfo.userId;
							// 更新存储
							uni.setStorageSync('userInfo', JSON.stringify(userInfo));
						}
						
						this.userInfo = userInfo;
						console.log('已获取登录用户信息:', this.userInfo);
						
						// 加载公告详情
						this.loadNoticeDetail();
					} catch (e) {
						console.error('解析用户信息失败', e);
						this.userInfo = null;
						this.handleError('获取用户信息失败');
					}
				} else {
					console.log('本地无用户信息，尝试从云端获取');
					this.getUserInfoFromCloud();
				}
			},
			
			// 从云端获取用户信息
			getUserInfoFromCloud() {
				uni.showLoading({
					title: '加载中...'
				});
				
				uniCloud.callFunction({
					name: 'user',
					data: {
						action: 'getUserInfo'
					},
					success: (res) => {
						uni.hideLoading();
						
						if (res.result.code === 0 && res.result.data) {
							// 完整保存用户信息，确保包含_id字段
							this.userInfo = {
								...res.result.data,
								_id: res.result.data.userId
							};
							uni.setStorageSync('userInfo', JSON.stringify(this.userInfo));
							
							// 加载公告详情
							this.loadNoticeDetail();
						} else {
							this.handleError('获取用户信息失败');
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('调用获取用户信息云函数失败', err);
						this.handleError('网络错误，请重试');
					}
				});
			},
			
			// 加载公告详情
			loadNoticeDetail() {
				uni.showLoading({
					title: '加载中...'
				});
				
				uniCloud.callFunction({
					name: 'getNoticeDetail',
					data: {
						id: this.noticeId
					},
					success: (res) => {
						uni.hideLoading();
						this.loading = false;
						
						if (res.result.code === 0 && res.result.data) {
							const noticeData = res.result.data;
							
							// 检查是否为当前用户发布的公告
							if (this.userInfo._id !== noticeData.userId && this.userInfo._id !== noticeData.creator_id) {
								this.handleError('您无权编辑此公告');
								return;
							}
							
							// 填充表单数据
							this.formData = {
								title: noticeData.title || '',
								content: noticeData.content || '',
								summary: noticeData.summary || '',
								category: noticeData.category || '赛事通知',
								tags: noticeData.tags || '',
								publishDate: this.formatDate(noticeData.publishDate) || this.currentDate,
								endDate: this.formatDate(noticeData.endDate) || '',
								importance: noticeData.importance || '普通',
								language: noticeData.language || 'zh-CN',
								type: noticeData.type || 'notice',
								isPublished: noticeData.isPublished !== false,
								showInBanner: noticeData.showInBanner || false,
								bannerImage: noticeData.bannerImage || {}
							};
							
							// 设置下拉框索引
							this.categoryIndex = this.categoryOptions.findIndex(item => item === this.formData.category);
							if (this.categoryIndex < 0) this.categoryIndex = 0;
							
							this.noticeTypeIndex = this.formData.type === 'activity' ? 1 : 0;
							
							this.importanceIndex = this.importanceOptions.findIndex(item => item === this.formData.importance);
							if (this.importanceIndex < 0) this.importanceIndex = 0;
							
							this.languageIndex = this.formData.language === 'en' ? 1 : 0;
						} else {
							this.handleError(res.result.message || '获取公告详情失败');
						}
					},
					fail: (err) => {
						uni.hideLoading();
						this.loading = false;
						console.error('获取公告详情失败:', err);
						this.handleError('网络错误，请重试');
					}
				});
			},
			
			// 提交表单
			submitForm() {
				// 表单验证
				if (!this.formData.title) {
					this.showToast('请输入公告标题');
					return;
				}
				
				if (!this.formData.content) {
					this.showToast('请输入公告内容');
					return;
				}
				
				if (!this.formData.summary) {
					this.showToast('请输入公告摘要');
					return;
				}
				
				if (!this.formData.tags) {
					this.showToast('请输入公告标签');
					return;
				}
				
				this.submitting = true;
				uni.showLoading({
					title: '更新中...'
				});
				
				// 将标签字符串转为数组
				const tagsArray = this.formData.tags.split(',').map(tag => tag.trim()).filter(tag => tag);
				
				// 准备更新数据
				const updateData = {
					noticeId: this.noticeId,
					title: this.formData.title,
					content: this.formData.content,
					summary: this.formData.summary,
					category: this.formData.category,
					tags: tagsArray,
					publishDate: this.formData.publishDate,
					endDate: this.formData.endDate || '',
					importance: this.formData.importance,
					language: this.formData.language,
					type: this.formData.type,
					isPublished: this.formData.isPublished,
					showInBanner: this.formData.showInBanner,
					bannerImage: this.formData.bannerImage,
					userId: this.userInfo._id,
					isImportant: this.formData.importance === '重要'
				};
				
				// 调用云函数更新公告
				uniCloud.callFunction({
					name: 'updateNotice',
					data: updateData,
					success: (res) => {
						this.submitting = false;
						uni.hideLoading();
						
						if (res.result.code === 0) {
							uni.showToast({
								title: '更新成功',
								icon: 'success'
							});
							
							// 延迟返回
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showModal({
								title: '更新失败',
								content: res.result.message || '未知错误',
								showCancel: false
							});
						}
					},
					fail: (err) => {
						this.submitting = false;
						uni.hideLoading();
						console.error('更新公告失败:', err);
						
						uni.showModal({
							title: '更新失败',
							content: '网络错误，请重试',
							showCancel: false
						});
					}
				});
			},
			
			// 处理错误
			handleError(message) {
				uni.showModal({
					title: '提示',
					content: message,
					showCancel: false,
					success: () => {
						uni.navigateBack();
					}
				});
			},
			
			// 显示提示
			showToast(message) {
				uni.showToast({
					title: message,
					icon: 'none'
				});
			},
			
			// 绑定分类选择
			bindCategoryChange(e) {
				this.categoryIndex = e.detail.value;
				this.formData.category = this.categoryOptions[this.categoryIndex];
			},
			
			// 绑定公告类型
			bindNoticeTypeChange(e) {
				this.noticeTypeIndex = e.detail.value;
				this.formData.type = this.noticeTypeIndex == 0 ? 'notice' : 'activity';
			},
			
			// 绑定日期
			bindDateChange(e) {
				this.formData.publishDate = e.detail.value;
				
				// 确保结束日期不早于发布日期
				if (this.formData.endDate && this.formData.endDate < this.formData.publishDate) {
					this.formData.endDate = '';
				}
			},
			
			// 绑定结束日期
			bindEndDateChange(e) {
				this.formData.endDate = e.detail.value;
			},
			
			// 绑定重要程度
			bindImportanceChange(e) {
				this.importanceIndex = e.detail.value;
				this.formData.importance = this.importanceOptions[this.importanceIndex];
			},
			
			// 绑定轮播显示
			bindShowInBannerChange(e) {
				this.formData.showInBanner = e.detail.value;
			},
			
			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '';
				
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style>
	@import "../admin/app.css";
	
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.form-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.section-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.section-desc {
		font-size: 26rpx;
		color: #999;
		margin-bottom: 30rpx;
		display: block;
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.form-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.required:after {
		content: ' *';
		color: #ff4d4f;
	}
	
	.form-desc {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.form-input {
		width: 100%;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.textarea-container {
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 20rpx;
	}
	
	.form-textarea {
		width: 100%;
		height: 300rpx;
		font-size: 28rpx;
		line-height: 1.5;
	}
	
	.form-picker {
		width: 100%;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}
	
	.picker-value {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.switch-container {
		display: flex;
		align-items: center;
	}
	
	.switch-label {
		font-size: 28rpx;
		color: #333;
		margin-left: 20rpx;
	}
	
	.submit-section {
		padding: 20rpx 0 50rpx;
	}
	
	.submit-btn {
		width: 100%;
		height: 90rpx;
		background-color: #1BAE76;
		color: #fff;
		border-radius: 8rpx;
		font-size: 32rpx;
		line-height: 90rpx;
	}
	
	.submit-btn[disabled] {
		background-color: #ccc;
		color: #fff;
	}
</style> 